/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.ohos.core;

import io.sentry.Breadcrumb;
import io.sentry.IHub;
import io.sentry.SentryLevel;
import io.sentry.transport.CurrentDateProvider;
import io.sentry.transport.ICurrentDateProvider;
import ohos.aafwk.ability.LifecycleObserver;
import ohos.aafwk.content.Intent;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
 * LifecycleWatcher
 *
 * @since 2021-06-01
 */
final class LifecycleWatcher extends LifecycleObserver {
    private final AtomicLong mLastUpdatedSession = new AtomicLong(0L);

    private final long sessionIntervalMillis;

    private @Nullable TimerTask timerTask;
    private final @NotNull Timer timer = new Timer(true);
    private final @NotNull IHub hub;
    private final boolean isEnableSessionTracking;
    private final boolean isEnableAppLifecycleBreadcrumbs;
    private final @NotNull AtomicBoolean runningSession = new AtomicBoolean();

    private final @NotNull ICurrentDateProvider currentDateProvider;

    LifecycleWatcher(
        final @NotNull IHub hub,
        final long sessionIntervalMillis,
        final boolean isEnableSessionTracking,
        final boolean isEnableAppLifecycleBreadcrumbs) {
        this(
            hub,
            sessionIntervalMillis,
            isEnableSessionTracking,
            isEnableAppLifecycleBreadcrumbs,
            CurrentDateProvider.getInstance());
    }

    LifecycleWatcher(
        final @NotNull IHub hub,
        final long sessionIntervalMillis,
        final boolean isEnableSessionTracking,
        final boolean isEnableAppLifecycleBreadcrumbs,
        final @NotNull ICurrentDateProvider currentDateProvider) {
        this.sessionIntervalMillis = sessionIntervalMillis;
        this.isEnableSessionTracking = isEnableSessionTracking;
        this.isEnableAppLifecycleBreadcrumbs = isEnableAppLifecycleBreadcrumbs;
        this.hub = hub;
        this.currentDateProvider = currentDateProvider;
    }

    // App goes to foreground

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        startSession();
        addAppBreadcrumb("foreground");
    }

    private void startSession() {
        if (isEnableSessionTracking) {
            cancelTask();

            final long currentTimeMillis = currentDateProvider.getCurrentTimeMillis();
            final long lastUpdatedSession = this.mLastUpdatedSession.get();

            if (lastUpdatedSession == 0L
                || (lastUpdatedSession + sessionIntervalMillis) <= currentTimeMillis) {
                addSessionBreadcrumb("start");
                hub.startSession();
                runningSession.set(true);
            }
            this.mLastUpdatedSession.set(currentTimeMillis);
        }
    }

    // App went to background and triggered this callback after 700ms
    // as no new screen was shown

    @Override
    public void onBackground() {
        super.onBackground();
        if (isEnableSessionTracking) {
            final long currentTimeMillis = currentDateProvider.getCurrentTimeMillis();
            this.mLastUpdatedSession.set(currentTimeMillis);

            scheduleEndSession();
        }

        addAppBreadcrumb("background");
    }

    private void scheduleEndSession() {
        cancelTask();
        timerTask =
            new TimerTask() {
                @Override
                public void run() {
                    addSessionBreadcrumb("end");
                    hub.endSession();
                    runningSession.set(false);
                }
            };

        timer.schedule(timerTask, sessionIntervalMillis);
    }

    private void cancelTask() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    private void addAppBreadcrumb(final @NotNull String state) {
        if (isEnableAppLifecycleBreadcrumbs) {
            final Breadcrumb breadcrumb = new Breadcrumb();
            breadcrumb.setType("navigation");
            breadcrumb.setData("state", state);
            breadcrumb.setCategory("app.lifecycle");
            breadcrumb.setLevel(SentryLevel.INFO);
            hub.addBreadcrumb(breadcrumb);
        }
    }

    private void addSessionBreadcrumb(final @NotNull String state) {
        final Breadcrumb breadcrumb = new Breadcrumb();
        breadcrumb.setType("session");
        breadcrumb.setData("state", state);
        breadcrumb.setCategory("app.lifecycle");
        breadcrumb.setLevel(SentryLevel.INFO);
        hub.addBreadcrumb(breadcrumb);
    }

    @TestOnly
    @NotNull
    AtomicBoolean isRunningSession() {
        return runningSession;
    }

    @TestOnly
    @Nullable
    TimerTask getTimerTask() {
        return timerTask;
    }
}
